// pages/search/search.js
import request from '../../utils/request';
let timer = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent:'', //placeholder的内容
    hotList:[], //热搜榜的数据
    searchContent:'', //用户输入的表单项数据
    searchList:[], //搜索模糊匹配的数据
    historyList:[], //历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取初始化数据
    this.getInitData();
    this.getSearchHistory();
    
  },
  //清楚搜索框内容
  clearSearchContent(){
    this.setData({
      searchContent:'',
      searchList:[]
    })
  },
  //清除历史记录
  clearHistory(){
    wx.removeStorageSync('searchHistory');
    this.setData({
      historyList:[]
    })
  },
  //获取本地历史记录的功能函数
  getSearchHistory(){
   let historyList = wx.getStorageSync('searchHistory');
   if (historyList) {
     this.setData({
      historyList
     })
   }
  },

  //获取初始化数据
  async getInitData(){
    //默认搜索关键字
    let placeholderContent =await request('/search/default');
    //热搜榜
    let hotList = await request('/search/hot/detail');
    this.setData({
      placeholderContent: placeholderContent.data.showKeyword,
      hotList: hotList.data
    })
  },

  //表单项内容发生改变
  handleInputChange(event){
    this.setData({
      searchContent: event.detail.value.trim()
    })
    //防抖函数
    clearTimeout(timer);
    timer =setTimeout(() => {
      this.getSearchList();
    },500)
  },

  //获取搜索数据的功能函数
  async getSearchList(){
    //发送请求获取关键字模糊匹配的数据
    if (!this.data.searchContent) {
      this.setData({
        searchList:''
      })
      return
    }
    let searchList = await request('/search',{keywords: this.data.searchContent, limit: 10})
    this.setData({
      searchList: searchList.result.songs
    })
    let {historyList, searchContent} = this.data;
    if (historyList.indexOf(searchContent) !== -1) {
      historyList.splice(historyList.indexOf(searchContent),1)
    }
    historyList.unshift(searchContent);
    this.setData({
      historyList
    })
    wx.setStorageSync('searchHistory', historyList);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})